<?php
/**
 *  @author: Rick van Schalkwijk
 * 	@date:	March 19, 2012
 *  @version: 0.0.1
 *
 *  Changes
 *  0.0.1
 *  Rick Created file
 *  Rick Added SingleTon
 *  Rick Added __destructor() and __constructor()
 *
 */

class fileHandler {

	// object instance
	private static $instance;
	 private $baseUrl    = null;

	private $controllerDir = "/controller/";
	private $viewDir = "/view/";

	private function __construct() {
		$fileController  = $this->controllerDir . "defaultController.php";
		$fileView		 = $this->viewDir . "defaultView.php";
	}
	private function __clone() {}

	/**
	 *
	 */
	public static function getInstance() {
			
		if (!fileHandler::$instance instanceof self) {
			fileHandler::$instance = new self();
		}

		return fileHandler::$instance;
	}
	
	public function copyFile( $path, $filename, $source ) {

		$newfile = $path . "/" .  $filename;

		if(!copy($source, $newfile)){
			log::fatal('Could not copy the file', $this, 'copyFile()');
			return;
		}
	}

	public function makeDir( $structure, $chmodMode ){

		$slash = '/';
		
		if(!@mkdir( $structure . $slash, $chmodMode, true ) ){
			var_dump(BASE_DIR);
			log::fatal('Could not make dir structure', $this, 'makeDir()');

			return false;
		}

		return true;
	}

	public function writable($filename) {
		if(!is_writable($filename)){
			Log::fatal('File is not writable, check the permissions', $this, 'writable()');
			return;
		}
	}

	// PASAL CASE ROCKS
	public function ExtCheck(){
		$filename = $_FILES['files']['tmp_name']; // original filename
		$validext = array( '.jpg' , '.gif' , '.png' );


		if($ext == 'gif')
		{
			echo 'The file is an gif. Good!';
		}else{
			echo 'Too bad the file is not a gif file!';
		}
	}

	/**
	 * Returns base url
	 *
	 * @return string
	 */
	public function baseUrl() {
		
		 if( $this->baseUrl ) {
            
            return $this->baseUrl;
        }
        

		$request_uri = rtrim( $_SERVER['REQUEST_URI'], '/' );

		$baseUrl = '';

		if( isset($_GET['route']) == true ) {
			$baseUrl .= rtrim( str_replace( rtrim( $_GET['route'] , '/' ), '', $request_uri ), '/' );
			$baseUrl = explode('/?', $baseUrl);
			$baseUrl = $baseUrl[0];
		} else {

			$baseUrl .= $request_uri;
		}

		return $this->baseUrl = $baseUrl;
	}

	public function uploadFile( $uploadFolder ){
               
    		$file_path = "/uploads/" . $uploadFolder;
	    	$target_path = $_SERVER['DOCUMENT_ROOT'] . $this->baseUrl() .$file_path .DIRSEP. basename( $_FILES['uploadedfile']['name']);
                if( move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target_path) ) {
                    return true;
                }else{
                    return false;
                }
    }
}
